import http from '@/api/http'
// import { AxiosPromise } from 'axios'
import { structurePredictRequest } from '@/app-model/structure'
import type { ApiResponseItems, ApiResponseSpec, AppMeta, AppSpec, fileOutput, jobMeta, OutputMap, PageView, result as JobResult, result, } from '@/app-model'
import { jobMetaExample } from '@/app-model'
import axios, { AxiosPromise, AxiosRequestConfig } from 'axios'
import $request from '@/utils/starlightRequest'
import { stringFile } from '@/app-model/graph-ppis'
import { ElNotification } from 'element-plus'
import { FileInfo, FileMeta, fileVerbose } from '@/app-model/file'
import store, { UserType } from '@/store'
// Mock apis
const mockQueryTime = 1000 * 0.5
export interface LoginRequest {
  username: string
  password: string
}

export const sendEmailCode = (email: string): Promise<any> => {
  return http.post('/message/email/code', { email })
}

export const login = (r: LoginRequest): Promise<any> => {
  return http.post('login', r)
}

export const uploadFile = (spath: string, file: File, settings?: AxiosRequestConfig): Promise<any> => {
  // 原 bioSim API 启用
  if (spath.startsWith('platform://')) {
    const data = new FormData()
    data.append('file', file)
    // Not A real file upload API.
    return http.post('api/similarity/upload_pdb/', data)
  }
  // 原 starlight API TODO
  if (spath.startsWith('file://')) {
    let settings = {} as AxiosRequestConfig
    settings
    return $request(settings)
  }
  return new Promise((resolve, reject) => {
    if (spath == "ok") {
      resolve("ok")
    } else {
      reject("false")
    }
  })
}


export const submitAppTask = (app: string, params: any, runtime_params: any): Promise<ApiResponseItems<string>> => {
  if (!runtime_params?.partition) {
    runtime_params = Object.assign(runtime_params, {
      cluster: 'k8s_venus',
      partition: 'venus-cpu',
      cpu: 1,
      memory: 5,
      userMode: "starlight",
    })
  }
  return http.post('/job/submit', {
    app,
    params,
    runtime_params
  })
}

// export const getJobResult = (jobindex: string): Promise<ApiResponseSpec<JobResult>> => {
//   if (jobindex === 'example') {
//     return new Promise((resolve, reject) => {
//       let outputs = {
//         "outputs_raw": {
//           "output1": {
//             class: "File",
//             checksum: "sha1$93ecfc6be24744aa31463abb550a83474bf06cfa",
//             location: "file:///GPUFS/app/bihu/spooler/graphppis-26111427j19n/log.job",
//             size: 1165,
//           },
//           "output10": 1365413,
//           "output11": "aaaaaaa",
//         } as OutputMap
//       }
//       let spec = Object.assign(outputs, jobMetaExample)
//       setTimeout(() => {
//         resolve({ spec, code: 200, uuid: "0000" })
//       }, mockQueryTime)
//     })
//   }
//   return http.get('/job/result/' + jobindex)
// }
export const getJobResult = (jobindex: string, appname: string): Promise<JobResult> => {
  if (jobindex === 'example') {
    return new Promise((resolve, reject) => {
      let outputs = {
        "outputs": {
          "output1": {
            class: "file",
            file: {
              uri: "/1.txt",
              meta: {
                mime: 'text/plain',
              }
            } as stringFile
          },
          "output2": {
            class: "file",
            file: {
              uri: "/model_1.pdb",
              meta: {
                mime: 'chemical/pdb',
              }
            } as stringFile
          },
          "output3": {
            class: "files",
            files: [({
              uri: "../../src/assets/logo.png",
              meta: {
                mime: 'image/png',
              }
            } as stringFile),
            ({
              uri: "../../src/assets/1.jpg",
              meta: {
                mime: 'image/png',
              }
            } as stringFile),
            ({
              uri: "../../src/assets/1.jpg",
              meta: {
                mime: 'image/png',
              }
            } as stringFile),
            ({
              uri: "../../src/assets/logo.png",
              meta: {
                mime: 'image/png',
              }
            } as stringFile),
            ({
              uri: "../../src/assets/logo.png",
              meta: {
                mime: 'image/png',
              }
            } as stringFile),
            ({
              uri: "../../src/assets/logo.png",
              meta: {
                mime: 'image/png',
              }
            } as stringFile),
            ({
              uri: "../../src/assets/logo.png",
              meta: {
                mime: 'image/png',
              }
            } as stringFile),
            ]
          },
          "output4": {
            class: "files",
            files: [({
              uri: "/ranked_0.pdb",
              meta: {
                mime: 'chemical/pdb',
              }
            } as stringFile),
            ({
              uri: "/ranked_1.pdb",
              meta: {
                mime: 'chemical/pdb',
              }
            } as stringFile),
            ({
              uri: "/ranked_2.pdb",
              meta: {
                mime: 'chemical/pdb',
              }
            } as stringFile),
            ({
              uri: "/ranked_3.pdb",
              meta: {
                mime: 'chemical/pdb',
              }
            } as stringFile),
            ({
              uri: "/ranked_4.pdb",
              meta: {
                mime: 'chemical/pdb',
              }
            } as stringFile),
            ]
          },
          "output5": {
            class: "files",
            files: [({
              uri: "../../src/assets/1.jpg",
              meta: {
                mime: 'image/png',
              }
            } as stringFile),
            ({
              uri: "/2.txt",
              meta: {
                mime: 'text/plain',
              }
            } as stringFile),
            ({
              uri: "../../src/assets/logo.png",
              meta: {
                mime: 'image/png',
              }
            } as stringFile),
            ({
              uri: "../../src/assets/logo.png",
              meta: {
                mime: 'image/png',
              }
            } as stringFile),
            ]
          },
          "output6": {
            class: "files",
            files: [({
              uri: "/model_1.pdb",
              meta: {
                mime: 'chemical/pdb',
              }
            } as stringFile),
            ({
              uri: "/ranked_0.pdb",
              meta: {
                mime: 'chemical/pdb',
              }
            } as stringFile),
            ({
              uri: "/ranked_1.pdb",
              meta: {
                mime: 'chemical/pdb',
              }
            } as stringFile),
            ({
              uri: "/3.txt",
              meta: {
                mime: 'text/plain',
              }
            } as stringFile),
            ]
          },

          "output7": {
            class: "file",
            file: {
              uri: "../../src/assets/1.jpg",
              meta: {
                mime: 'image/png',
              }
            } as stringFile
          },
          "output8": {
            class: "files",
            files: [({
              uri: "/ranked_2.pdb",
              meta: {
                mime: 'chemical/pdb',
              }
            } as stringFile),
            ({
              uri: "/ranked_3.pdb",
              meta: {
                mime: 'chemical/pdb',
              }
            } as stringFile),
            ({
              uri: "/4.txt",
              meta: {
                mime: 'text/plain',
              }
            } as stringFile),

            ({
              uri: "../../src/assets/1.jpg",
              meta: {
                mime: 'image/png',
              }
            } as stringFile),
            ({
              uri: "/model_1.pdb",
              meta: {
                mime: 'chemical/pdb',
              }
            } as stringFile),

            ({
              uri: "../../src/assets/logo.png",
              meta: {
                mime: 'image/png',
              }
            } as stringFile),

            ({
              uri: "../../src/assets/logo.png",
              meta: {
                mime: 'image/png',
              }
            } as stringFile),
            ]
          },
          "output9": {
            class: "files",
            files: [

              ({
                uri: "../../src/assets/logo.png",
                meta: {
                  mime: 'image/png',
                }
              } as stringFile),
              ({
                uri: "/model_1.pdb",
                meta: {
                  mime: 'chemical/pdb',
                }
              } as stringFile),

              ({
                uri: "../../src/assets/logo.png",
                meta: {
                  mime: 'image/png',
                }
              } as stringFile),
              ({
                uri: "/ranked_4.pdb",
                meta: {
                  mime: 'chemical/pdb',
                }
              } as stringFile),

              ({
                uri: "../../src/assets/logo.png",
                meta: {
                  mime: 'image/png',
                }
              } as stringFile),
              ({
                uri: "/5.txt",
                meta: {
                  mime: 'text/plain',
                }
              } as stringFile),

              ({
                uri: "../../src/assets/logo.png",
                meta: {
                  mime: 'image/png',
                }
              } as stringFile),
              ({
                uri: "../../src/assets/logo.png",
                meta: {
                  mime: 'image/png',
                }
              } as stringFile),
              ({
                uri: "../../src/assets/logo.png",
                meta: {
                  mime: 'image/png',
                }
              } as stringFile),
              ({
                uri: "../../src/assets/logo.png",
                meta: {
                  mime: 'image/png',
                }
              } as stringFile),
              ({
                uri: "../../src/assets/logo.png",
                meta: {
                  mime: 'image/png',
                }
              } as stringFile),
              ({
                uri: "../../src/assets/logo.png",
                meta: {
                  mime: 'image/png',
                }
              } as stringFile),
            ]
          },
          "output10": 1365413,
          "output11": "aaaaaaa",
        } as OutputMap
      }
      let mockData = Object.assign(outputs, jobMetaExample)
      setTimeout(() => {
        resolve(mockData)
      }, mockQueryTime)
    })
  }
  return new Promise((resolve, reject) => { reject("Not Ok Yet") })
}
/*  
  region: 选择的领域
  params: 其他扩展参数，如分页控制等
  结果：
  spec: App 列表
    name: 索引名称， title: 显示给用户的名称,
    icon: 图片，如地址为 https://starlight.nscc-gz.cn/api/mei/acorn/2e2f701b-1ee2-4d7e-988e-3d36c8343b80
    type: 类型区分
 */
export const getApps = (params?: any): Promise<ApiResponseItems<AppMeta>> => {
  // not use direct after ...
  // return http.get('/app', { params })
  return Promise.resolve({ "uuid": "c21fbd9e-240a-4a1c-beae-4444fa9527e9", "code": 200, "info": "", "kind": "", "total": 4, "spec": [{ "id": 1444, "name": "graphppis-v2", "title": "GraphPPIS", "icon": "c4733b0e-0a13-43e4-bc7a-6398e782b2da", "description": "蛋白质结合位点预测算法", "type": 1, "region": "site_predict" }, { "id": 1445, "name": "alphaFold2_bio", "title": "Alpha Fold 2.1.2", "icon": "/img1.jpg", "description": "Alpha Fold 2.1.2; 支持多聚体", "type": 1 }, { "id": 1446, "name": "graphsite", "title": "GraphSite", "icon": "/img2.jpg", "description": "蛋白质DNA结合位点预测", "type": 1 }, { "id": 1447, "name": "rscb-getpdb", "title": "rscb-getpdb", "icon": "/img3.jpg", "description": "数据下载", "type": 1 }, { "id": 1447, "name": "rscb-getpdb", "title": "demo", "icon": "/img3.jpg", "description": "数据下载", "type": 1 }, { "id": 1447, "name": "rscb-getpdb", "title": "demo", "icon": "/img3.jpg", "description": "数据下载", "type": 1 }, { "id": 1447, "name": "rscb-getpdb", "title": "demo", "icon": "/img3.jpg", "description": "数据下载", "type": 1 }] })
}

export const getAppSpec = async (app: string, params?: any): Promise<AppSpec> => {
  let mockAppSpec: AppSpec = {
    "id": 1406,
    "name": "graphppis",
    "render": {
      "id": "widgets-root",
      "type": "container",
      "name": "",
      "offset": 0,
      "width": 24,
      "label": "根组件",
      "attr": {},
      "data": [
        {
          "id": "info1",
          "type": "info",
          "name": "",
          "offset": 0,
          "width": 24,
          "label": "",
          "attr": {
            "visible": true,
            "default": "<h2 style=\"box-sizing: inherit; color: #303133; font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: #ffffff; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; text-align: center;\" data-v-67dea2ff=\"\"><span style=\"box-sizing: inherit; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; color: #000000; font-family: 'Microsoft Yahei', 微软雅黑, 宋体; font-size: 36px; font-weight: 600; text-align: justify; background-color: #ffffff; float: none; display: inline !important;\">GraphPPIS  : 基于深度图卷积网络的结构感知的蛋白质相互作用位点预测</span><br style=\"box-sizing: inherit; color: #303133; font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif; font-size: 18.72px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: bold; letter-spacing: normal; orphans: 2; text-align: center; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: #ffffff; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;\" /><span style=\"color: #303133; font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif; font-size: 18.72px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: bold; letter-spacing: normal; orphans: 2; text-align: center; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: #ffffff; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; display: inline !important; float: none;\">ref:&nbsp;</span><span style=\"box-sizing: inherit; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: bold; letter-spacing: normal; orphans: 2; text-align: center; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: #ffffff; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; color: #333333; font-family: arial; font-size: 16px;\">https://doi.org/10.1093/bioinformatics/btab643</span></h2>"
          },
          "data": []
        },
        {
          "id": "text1",
          "type": "text",
          "name": "pdbID",
          "offset": 0,
          "width": 24,
          "label": "pdbID",
          "attr": {
            "placeholder": "",
            "required": false,
            "disabled": false,
            "visible": true,
            "rules": "",
            "default": "1r8s"
          },
          "data": []
        },
        {
          "id": "rfbPath1",
          "type": "rfbPath",
          "name": "pdb",
          "offset": 0,
          "width": 24,
          "label": "pdb",
          "attr": {
            "placeholder": "",
            "default": "",
            "visible": true,
            "required": false,
            "extends": {
              "accept": ".pdb",
            },
            "rules": ""
          },
          "data": []
        },
        {
          "id": "text2",
          "type": "text",
          "name": "chain",
          "offset": 0,
          "width": 24,
          "label": "chain",
          "attr": {
            "placeholder": "",
            "required": true,
            "disabled": false,
            "visible": true,
            "rules": "",
            "default": "E"
          },
          "data": []
        },
        {
          "id": "list1",
          "type": "list",
          "name": "mode",
          "offset": 0,
          "width": 24,
          "label": "mode",
          "attr": {
            "required": false,
            "disabled": false,
            "visible": true,
            "options": [
              {
                "label": "fast",
                "value": "fast",
                "number": false,
                "disabled": false,
                "selected": false
              },
              {
                "label": "slow",
                "value": "slow",
                "disabled": false
              }
            ],
            "default": "fast"
          },
          "data": []
        },
      ]
    },
    "title": "GraphPPIS",
    "icon": "513e68a9-d6e0-4014-93af-2c912448e258",
    "type": 1,
    "description": "蛋白质结合位点预测算法"
  }
  if (app === 'graph-ppis') {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(mockAppSpec)
      }, mockQueryTime)
    })
  }
  if(app==='graphsite'){
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(JSON.parse(`{"id":1446,"name":"graphsite","title":"GraphSite","icon":"6f299aa6-0949-4b4b-8a51-f91d3ee497ca","description":"蛋白质DNA结合位点预测","type":1,"definition":"#!/usr/bin/env cwl-runner\\ncwlVersion: v1.0\\nclass: CommandLineTool\\nhints:\\n  - class: DockerRequirement\\n    dockerPull: \\"hub.starlight.nscc-gz.cn/nsccgz_duliang_1_public/deeplearning-1574907288:centos\\"\\nrequirements:\\n  EnvVarRequirement:\\n    envDef:\\n      pkl: $(inputs.pkl.location)\\n      pdb: $(inputs.pdb.location)\\n      use_evo: $(inputs.use_evo||\\"\\")\\nbaseCommand: [\\"/app/common/bio-platform/GraphSite/run.sh\\"]\\ninputs:\\n  use_evo:\\n    type: string?\\n  pdb:\\n    type: File\\n  pkl:\\n    type: File\\noutputs:\\n  result:\\n    type: File\\n    outputBinding:\\n      glob: \\"Results_*.txt\\"\\n  log:\\n    type: File\\n    outputBinding:\\n      glob: \\"log.job\\"\\n\\n","render":{"id":"widgets-root","type":"container","name":"","value":"","offset":0,"width":24,"label":"根组件","attr":{},"data":[{"id":"info1","type":"info","name":"","value":"","offset":0,"width":24,"label":"","attr":{"visible":true,"default":"<p class=\\"p1\\"><span class=\\"s1\\"><b>GraphSite&mdash;&mdash;</b></span><span class=\\"s2\\"><b>基于</b></span><span class=\\"s1\\"><b>AlphaFold2</b></span><span class=\\"s2\\"><b>和图</b></span><span class=\\"s1\\"><b>transformer</b></span><span class=\\"s2\\"><b>的蛋白质</b></span><span class=\\"s1\\"><b>-DNA</b></span><span class=\\"s2\\"><b>结合位点预测</b></span></p>\\n<p class=\\"p1\\"><span class=\\"s2\\"><span style=\\"color: #5b616b; font-family: 'system-ui', -apple-system, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; font-size: 16px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: #ffffff; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; display: inline !important; float: none;\\">doi: 10.1093/bib/bbab564.</span></span></p>"},"data":[]},{"id":"rfb1","type":"rfb","name":"pdb","value":"","offset":0,"width":24,"label":"pdb","attr":{"placeholder":"","default":"","visible":true,"required":true,"rules":"","fileOrDir":"file"},"data":[]},{"id":"rfb2","type":"rfb","name":"pkl","value":"","offset":0,"width":24,"label":"pkl","attr":{"placeholder":"","default":"","visible":true,"required":true,"rules":"","fileOrDir":"file"},"data":[]},{"id":"list1","type":"list","name":"use_evo","value":"","offset":0,"width":24,"label":"use_evo","attr":{"required":false,"disabled":false,"visible":true,"options":[{"label":"True","value":"True","number":false,"disabled":false,"selected":false},{"label":"False","value":"","disabled":false}],"default":""},"data":[]}]},"configs":{"runtime":{"0":"{","1":"\\"","2":"u","3":"s","4":"e","5":"r","6":"M","7":"o","8":"d","9":"e","10":"\\"","11":":","12":"\\"","13":"\\"","14":",","15":"\\"","16":"e","17":"n","18":"d","19":"p","20":"o","21":"i","22":"n","23":"t","24":"s","25":"\\"","26":":","27":"[","28":"]","29":",","30":"\\"","31":"e","32":"n","33":"v","34":"\\"","35":":","36":"{","37":"}","38":"}","cluster":{"attr":{"visible":true},"type":"cluster"},"endpoints":[],"env":{},"info":"","nodes":{"attr":{"visible":true},"type":"number"},"userMode":"starlight"}}}`))
      }, mockQueryTime)
    })
  }
  if(app==='alphaFold2_bio'){
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(JSON.parse(`{"id":1445,"name":"alphaFold2_bio","title":"Alpha Fold 2.1.2","icon":"2e2f701b-1ee2-4d7e-988e-3d36c8343b80","description":"Alpha Fold 2.1.2; 支持多聚体","type":1,"definition":"#!/usr/bin/env cwl-runner\\ncwlVersion: v1.0\\nclass: CommandLineTool\\nhints:\\n  - class: DockerRequirement\\n    dockerPull: \\"hub.starlight.nscc-gz.cn/nscc-gz_jiangli_public/alphafold:2.0.0-d26287e\\"\\nrequirements:\\n  EnvVarRequirement:\\n    envDef:\\n      fasta_paths: $(inputs.fasta_paths.location)\\n      AF_DIR: $(inputs.AF_DIR || '')\\n      output_dir: $(inputs.output_dir || '')\\n      DOWNLOAD_DIR: $(inputs.DOWNLOAD_DIR || '')\\n      db_preset: $(inputs.db_preset || '')\\n      model_preset: $(inputs.model_preset || '')\\n      max_template_date: $(inputs.max_template_date || '')\\n      run_relax: $(inputs.run_relax || '')\\n      enable_gpu_relax: $(inputs.enable_gpu_relax || '')\\n      is_prokaryote_list: $(inputs.is_prokaryote_list || '')\\n      use_precomputed_msas: $(inputs.use_precomputed_msas || '')\\nbaseCommand: [\\"bash\\"]\\narguments: [  \\"/app/common/alphafold/run-v2.1.2.sh\\"]\\ninputs:\\n  fasta_paths:\\n    type: File\\n  model_preset:\\n    type: string?\\n  db_preset:\\n    type: string?\\n  max_template_date:\\n    type: string?\\n  run_relax:\\n    type: string?\\n  use_gpu_relax:\\n    type: string?\\n  is_prokaryote_list:\\n    type: string?","render":{"id":"widgets-root","type":"container","name":"","value":"","offset":0,"width":24,"label":"根组件","attr":{},"data":[{"id":"info1","type":"info","name":"","value":"","offset":0,"width":24,"label":"","attr":{"default":"<p>&nbsp;</p>\\n<p>&nbsp;</p>","visible":true},"data":[]},{"id":"rfb1","type":"rfb","name":"fasta_paths","value":"","offset":0,"width":24,"label":"fasta_paths","attr":{"placeholder":"","default":"","visible":true,"required":true,"rules":"","fileOrDir":"file"},"data":[]},{"id":"list1","type":"list","name":"db_preset","value":"","offset":0,"width":24,"label":"db_preset","attr":{"required":false,"disabled":false,"visible":true,"options":[{"label":"full_dbs","value":"full_dbs","number":false,"disabled":false,"selected":false},{"label":"reduced_dbs","value":"reduced_dbs","disabled":false}],"default":"full_dbs"},"data":[]},{"id":"list4","type":"list","name":"model_preset","value":"","offset":0,"width":24,"label":"model_preset","attr":{"required":false,"disabled":false,"visible":true,"options":[{"label":"monomer","value":"monomer","number":false,"disabled":false,"selected":false},{"label":"monomer_casp14","value":"monomer_casp14","disabled":false},{"label":"monomer_ptm","value":"monomer_ptm","disabled":false},{"label":"multimer","value":"multimer","disabled":false}],"default":"monomer"},"data":[]},{"id":"text1","type":"text","name":"max_template_date","value":"","offset":0,"width":24,"label":"max_template_date","attr":{"placeholder":"","required":false,"disabled":false,"visible":true,"rules":"","default":"2020-05-14"},"data":[]},{"id":"list3","type":"list","name":"run_relax","value":"","offset":0,"width":24,"label":"run_relax","attr":{"required":false,"disabled":false,"visible":true,"options":[{"label":"True","value":"True","number":false,"disabled":false,"selected":false},{"label":"False","value":"False","disabled":false}],"default":"True"},"data":[]},{"id":"list5","type":"list","name":"enable_gpu_relax","value":"","offset":0,"width":24,"label":"enable_gpu_relax","attr":{"required":false,"disabled":false,"visible":true,"options":[{"label":"True","value":"True","number":false,"disabled":false,"selected":false},{"label":"False","value":"False","disabled":false}],"default":"True"},"data":[]},{"id":"list6","type":"list","name":"is_prokaryote_list","value":"","offset":0,"width":24,"label":"is_prokaryote_list","attr":{"required":false,"disabled":false,"visible":true,"options":[{"label":"True","value":"True","number":false,"disabled":false,"selected":false},{"label":"False","value":"False","disabled":false}],"default":"False"},"data":[]}]},"configs":{"runtime":{"cluster":{"attr":{"visible":true},"type":"cluster"},"endpoints":[],"env":{"PYTHONNOUSERSITE":"1","PYTHONPATH":"/app/common/alphafold/v2.1.2-python/lib/python3.8/site-packages"},"info":"<p><a href=\\"https://github.com/deepmind/alphafold\\">https://github.com/deepmind/alphafold</a></p>\\n<p>当前版本: &nbsp;v2.1.2</p>\\n<p>应用本身参数，更详细的说明参考官网：</p>\\n<ul>\\n<li>run_relax 是否进行弛豫过程</li>\\n<li>enable_gpu_relax 是否使用GPU进行弛豫</li>\\n<li>fasta_paths 为需要分析的序列文件</li>\\n<li>is_prokaryote_list 目标复合物来自原核生物（只用于多聚体的预测）</li>\\n<li>model_preset&nbsp; 选择预设的模型：\\n<ul>\\n<li>the monomer model</li>\\n<li>the monomer model with extra ensembling</li>\\n<li>monomer model with pTM head</li>\\n<li>multimer model</li>\\n</ul>\\n</li>\\n<li>db_preset 预设 MSA 数据库</li>\\n<li>max_template_date 计算数据库中已有的结构时，需要指定到发现前的时间</li>\\n</ul>\\n<p>&nbsp;</p>\\n<p>&nbsp;</p>","nodes":{"attr":{"visible":true},"type":"number"},"userMode":"starlight"}}}`))
      }, mockQueryTime)
    })
  }
  if(app==="rscb-getpdb"){
    
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(JSON.parse(`{"id":1447,"name":"rscb-getpdb","title":"rscb-getpdb","icon":"fef1ee7c-68ec-4a35-ba40-eac9b8ecd332","description":"数据下载","type":1,"definition":"#!/usr/bin/env cwl-runner\\ncwlVersion: v1.0\\nclass: CommandLineTool\\nhints:\\n  - class: DockerRequirement\\n    dockerPull: \\"hub.starlight.nscc-gz.cn/nsccgz_duliang_1_public/deeplearning-1574907288:centos\\"\\nrequirements:\\n  EnvVarRequirement:\\n    envDef:\\n      pdbID: $(inputs.pdbID)\\nbaseCommand: [\\"/app/common/bio-platform/tools/getPDB.sh\\"]\\ninputs:\\n  pdbID:\\n    type: string\\noutputs:\\n  fasta:\\n    type: File\\n    outputBinding:\\n      glob: \\"*.fasta\\"\\n  pdb:\\n    type: File\\n    outputBinding:\\n      glob: \\"*.pdb\\"\\n  cif:\\n    type: File\\n    outputBinding:\\n      glob: \\"*.cif\\"\\n  cif:\\n    type: File\\n    outputBinding:\\n      glob: \\"*.cif\\"\\n  pdbml:\\n    type: File\\n    outputBinding:\\n      glob: \\"*.xml.gz\\"\\n\\n","render":{"id":"widgets-root","type":"container","name":"","value":"","offset":0,"width":24,"label":"根组件","attr":{},"data":[{"id":"info1","type":"info","name":"","value":"","offset":0,"width":24,"label":"","attr":{"visible":true,"default":""},"data":[]},{"id":"text1","type":"text","name":"pdbID","value":"1r8s","offset":0,"width":24,"label":"pdbID","attr":{"placeholder":"","required":false,"disabled":false,"visible":true,"rules":"[0-9a-zA-Z]{4}","default":"1r8s"},"data":[]}]},"configs":{"runtime":{"0":"{","1":"\\"","2":"u","3":"s","4":"e","5":"r","6":"M","7":"o","8":"d","9":"e","10":"\\"","11":":","12":"\\"","13":"\\"","14":",","15":"\\"","16":"e","17":"n","18":"d","19":"p","20":"o","21":"i","22":"n","23":"t","24":"s","25":"\\"","26":":","27":"[","28":"]","29":",","30":"\\"","31":"e","32":"n","33":"v","34":"\\"","35":":","36":"{","37":"}","38":"}","cluster":{"attr":{"visible":true},"type":"cluster"},"endpoints":[],"env":{},"info":"<p>Download Files From <a href=\\"https://www.rcsb.org/\\">https://www.rcsb.org/</a>&nbsp;</p>","nodes":{"attr":{"visible":true},"type":"number"},"userMode":"starlight"}}}`))
      }, mockQueryTime)
    })
  }
  let ret = await http.get('/app/' + app).catch(err => {
    throw (err)
  })
  let appData = ret.data?.spec || (ret as any).spec
  if (typeof appData.render === "string") {
    appData.render = JSON.parse(appData.render)
  }
  return (appData as AppSpec)
}

export const getJobs = (params?: any): Promise<ApiResponseItems<jobMeta>> => {
  console.log("params:", params)
  return http.get('/job/result', { params })
}

export const getFileSystemList = (params?: any): Promise<any> => {
  return $request({
    url: '/api/storage/user_storage_path',
    method: 'get',
    params,
    headers: { 'TIMEOUT': '15' },
  })
}

export const getDirInfo = (dirpath: string, params?: any): Promise<any> => {
  let query = Object.assign({
    dir: dirpath,
  }, params)
  console.log(query)
  return $request({
    url: '/api/storage/dir_info',
    method: 'get',
    params: query,
    headers: { 'TIMEOUT': '15' },
  })
}

export function uploadFileDirectToStarlight(params: any, data: Blob, settings: any) {
  if (!settings) {
    settings = {}
  }
  var contentType = 'application/octet-stream'
  var mysettings = Object.assign(settings, {
    url: '/api/storage/upload',
    method: 'put',
    params: params,
    timeout: 0,
    data
  })
  if (!mysettings.headers) {
    mysettings.headers = {}
  }
  mysettings.headers['Content-Type'] = contentType
  return $request(mysettings)
}


export function uploadFileDirect(params: any, data: Blob, settings: any): Promise<ApiResponseSpec<FileInfo>> {
  if (!settings) {
    settings = {}
  }
  var contentType = 'application/octet-stream'
  var mysettings = Object.assign(settings, {
    url: '/storage/upload',
    method: 'put',
    params: params,
    timeout: 0,
    data
  })
  if (!mysettings.headers) {
    mysettings.headers = {}
  }
  mysettings.headers['Content-Type'] = contentType
  // return $request(mysettings)
  return http.request(mysettings)
}

export function uploadFileDirectSimple(filename: string, fileObj: File, params?: any, settings?: any): Promise<ApiResponseSpec<FileInfo>> {
  let blob = new Blob([fileObj])
  var filesize = blob.size
  // if (filesize > 1024 * 1024 * 5) {
  //   ElNotification({
  //     title: '只允许小于5MB的文件',
  //     type: 'warning',
  //     duration: 10000
  //   })
  //   return Promise.reject("只允许小于5MB的文件")
  // }
  console.log("parmas ? :", params)
  let paramsAtt = {
    ...params,
    file: filename,
    overwrite: false || (settings && settings.overwrite)
  }
  return uploadFileDirect(paramsAtt, blob, settings)
}

export function mkDirInput(dirname: string) {
  let params = {
    file: "@input/" + store.state.user.name + "/" + dirname
  }
  return http.post("/storage/mkdir", null, { params })
}

// 返回文本文件的内容
// export const previewFile = (url: string | fileVerbose, size: number = 1000, page: number = 1): Promise<ApiResponseSpec<PageView>> => {
//   let file = ""
//   let [sha1, dir, ext] = ["", "", "", ""]
//   if (typeof url === "object") {
//     file = url.location
//     if (url.checksum?.startsWith("sha1$")) {
//       sha1 = url.checksum.slice("sha1$".length)
//     } else {
//       return http.get("/storage/view", {
//         params: { page, size, file, sha1, dir, ext },
//       })
//     }
//     ext = url.meta.ext
//     if (file.startsWith("file://")) {
//       file = file.slice("file://".length)
//     }
//     if (file.startsWith("@") || file.startsWith("#")) {
//       dir = file.split("/")[0]
//       dir = dir.slice(1)
//     }
//     file = ""
//   } else {
//     file = url
//   }
//   return http.get("/storage/view", {
//     params: { page, size, file, sha1, dir, ext },
//   })
// }

//对象复制
export const copy = <T>(obj: T): T => {
  return JSON.parse(JSON.stringify(obj))
}

// Orginal API
export const checkPredictStructureProjectName = (projName: string): Promise<any> => {
  return http.get('/predict/structure/check/', { params: { proj_name: projName } })
}

export const submitPredictStruct = (r: structurePredictRequest): Promise<any> => {
  return http.post('/predict/structure_submit/', r)
}



export const ConvertToObjectUrl = (url: string, fileName: string) => {
  return new Promise<string>((resolve, reject) => {
    var xhr = new XMLHttpRequest()
    xhr.open("GET", url, true)
    xhr.responseType = 'blob'
    if (store.state.user.type === UserType.StarlightUser) {
      xhr.setRequestHeader('Bihu-Token', store.state.user.token)
    } else if (store.state.user.type === UserType.EmailFreeUser) {
      xhr.setRequestHeader('Authorization', store.state.user.token)
    }
    xhr.onload = async function (res) {
      if (this.status === 200) {
        var type = xhr.getResponseHeader('Content-Type') || ""
        var blob = new Blob([this.response])
        console.log(blob)
        if (type === "application/json") {
          let txt = await blob.text().catch(err => {
            reject("下载文件失败" + err)
          })
          if (!txt) {
            return
          }
          try {
            let respData = JSON.parse(txt)
            if (respData && respData.code) {
              reject("下载文件失败" + respData.info)
              return
            }
          } catch (e) {
            console.log("Not Real Json File")
          }
        }
        var URL = window.URL || window.webkitURL
        var objectUrl = URL.createObjectURL(blob)
        resolve(objectUrl)
      }
    }
    xhr.send()
  })
}


// 返回文本文件的内容
export const getText = (url: string, size: number, page: number): Promise<{ text: string, total: number }> => {
  let text: string
  return new Promise((resolve, reject) => {
    axios.get(url).then(res => {
      text = res.data.slice(size * (page - 1), size * page)
      resolve({ text, total: res.data.length })
    }).catch(err => {
      reject(err)
    })
  })
}